package com.example.ndkjnidemo.home.arraylist

import android.util.Log
import com.blankj.utilcode.util.LogUtils

/**
 *
 * @ProjectName:    MyArrayList
 * @Package:        com.itfitness.myarraylist
 * @ClassName:      MyArrayList
 * @Description:     java类作用描述
 * @Author:         作者名
 * @CreateDate:     2021/3/14 11:26
 * @UpdateUser:     更新者：itfitness
 * @UpdateDate:     2021/3/14 11:26
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */
class MyArrayList {

    private val addr: Long //存储NDK层的ArrayList的地址

    companion object {

        // Used to load the 'native-lib' library on application startup.
        init {
            System.loadLibrary("ndk-jni")
        }
    }

    external fun createArrayList(): Long
    external fun get(addr: Long, index: Int): Int
    external fun add(addr: Long, element: Int)
    external fun remove(addr: Long, index: Int): Int
    external fun size(addr: Long): Int
    external fun release(addr: Long)

    init {
        addr = createArrayList()
        LogUtils.i("创建的地址", "$addr")
    }

    /**
     * 添加元素
     */
    fun add(element: Int) {
        add(addr, element)
    }

    /**
     * 获取元素
     */
    fun get(index: Int): Int {
        return get(addr, index)
    }

    /**
     * 获取大小
     */
    fun size(): Int {
        return size(addr)
    }

    /**
     * 移除并返回元素
     */
    fun remove(index: Int): Int {
        return remove(addr, index)
    }

    /**
     * GC回收的时候将C++的对象释放掉
     */
    @Throws(Throwable::class)
    protected fun finalize() {
        release(addr)
    }
}